const express = require('express');
const router = express.Router();
const myMulter = require('../lib/middleware/myMulter');
const verify = require('../lib/controller/verify');
const User = require('../database/redis/userDao');

router.get('/', function (req, res, next) {

    //退出登录
    if (req.query.msg === 'logout') {
        req.session.userId = null;
        res.redirect("/");
        return
    }

    //如果已经登录直接重定义
    if (req.session.userId) {
        res.redirect("/");
        return
    }

    res.render('login');
})

router.post('/', myMulter, async function (req, res, next) {
    let account = req.body.account;
    let password = req.body.password;
    let status = await verify.asyncLoginVerify(req, account, password);

    if (status === true) {
        //用户id信息写入session
        req.session.userId = await User.asyncGetIdByAccount(account);
        console.log(`123312fuck___${req.session.userId}`)

        //用户信息写入模板引擎
        res.locals.userData = await User.asyncGetDataById(req.session.userId);
        res.redirect('/');
        return
    }

    res.render('login');
})

module.exports = router;